package counter.com.baomidou.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import counter.com.baomidou.entity.Userinfo;
import counter.com.baomidou.mapper.UserinfoMapper;
import counter.com.baomidou.service.IUserinfoService;
import counter.com.common.Result;
import counter.com.configuration.TokenManager;
import counter.com.connproperty.login.LoginDeleteProperty;
import counter.com.connproperty.login.LoginEditProperty;
import counter.com.connproperty.login.LoginInfoProperty;
import counter.com.connproperty.UserInfoLoginProperty;
import counter.com.connproperty.login.LoginSearchProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-09-28
 */
@RestController
@RequestMapping("/userinfo")
public class UserinfoController {
    private static final int ROOT_ADMIN = 1;
    @Autowired
    UserinfoMapper userinfoMapper;
    @Autowired
    IUserinfoService service;

    private static int expire = 60 * 60 * 24 * 7;

    @PostMapping("/login")
    public Result login(@RequestBody LoginInfoProperty data, HttpServletRequest request, HttpServletResponse response) {
        LambdaQueryWrapper<Userinfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Userinfo::getUsername, data.getUsername());
        Userinfo userinfo = service.getOne(wrapper);
        if (userinfo != null) {
            if (userinfo.getPassword().equals(data.getPassword())) {
                TokenManager tokenManager = TokenManager.getInstance();
                String token = createToken();
//                response.addHeader("Set-Cookie", token);
//                CookieUtil.setCookie(request, response, "username", userinfo.getUsername(), expire);
//                CookieUtil.setCookie(request, response, "password", userinfo.getPassword(), expire);
//                CookieUtil.setCookie(request, response, "token", token, expire);
                tokenManager.addToken(token, userinfo.getUsername());
                return Result.success(new UserInfoLoginProperty(token, userinfo.getUsername(), userinfo.getPassword(), userinfo.getRoot()));
            } else {
                return Result.fail("密码错误");
            }
        } else {
            return Result.fail("没有此用户");
        }

    }

    private String createToken() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 30; i++) {
            int index = (int) (Math.floor(Math.random() * 36));
            if (index < 26) {
                char c = (char) ('a' + index);
                sb.append(c);
            } else {
                sb.append(index - 26);
            }
        }
        return sb.toString();
    }

    @PostMapping("/add")
    public Result add(@RequestBody @Validated LoginInfoProperty data) {
        Userinfo info = new Userinfo();
        info.setRoot(2);
        LambdaQueryWrapper<Userinfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Userinfo::getUsername, data.getUsername());
        Userinfo userinfo = userinfoMapper.selectOne(wrapper);
        if (userinfo == null) {
            info.setUsername(data.getUsername());
            info.setPassword(data.getPassword());
            userinfoMapper.insert(info);
            return Result.success("成功添加用户");
        } else {
            return Result.fail("用户已存在");
        }
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody LoginDeleteProperty data) {
        List<Integer> list = Arrays.asList(data.getIds());
        int removeCount = 0;
        for (Integer id : list) {
            Userinfo userinfo = service.getById(id);
            if (userinfo.getRoot() != ROOT_ADMIN) {
                if (service.removeById(id)) {
                    removeCount++;
                }
            }
        }
        if (removeCount > 0) {
            return Result.success("成功删除了" + removeCount + "条数据");
        } else {
            return Result.fail("删除失败");
        }
    }

    @PostMapping("/edit")
    public Result edit(@RequestBody @Validated LoginEditProperty data) {
        Userinfo user = service.getById(data.getId());
        if (user == null) {
            return Result.fail("选择了错误的用户");
        }
        user.setPassword(data.getPassword());
        user.setUsername(data.getUsername());
        if (service.updateById(user)) {
            return Result.success("更新成功");
        } else {
            return Result.fail("更新失败");
        }
    }

    @PostMapping("/search")
    public Result search(@RequestBody LoginSearchProperty data) {
        LambdaQueryWrapper<Userinfo> wrapper = new LambdaQueryWrapper<>();
//        wrapper.ne(Userinfo::getRoot, ROOT_ADMIN).orderByDesc(Userinfo::getId);
        //管理员的处理交给前端
        wrapper.orderByDesc(Userinfo::getId);
        Page<Userinfo> page = new Page<>(data.getPage(), data.getPagesize());
        IPage<Userinfo> iPage = service.page(page, wrapper);
        return Result.success(iPage);
    }
}
